﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using System.Text;

public partial class UserControls_SearchBox : System.Web.UI.UserControl
{
    // regular expression that removes characters that aren't a-z, 0-9, dash, 
    // underscore or space
    private static Regex purifyUrlRegex = new Regex("[^-a-zA-Z0-9_ ]", RegexOptions.Compiled);

    protected void Page_Load(object sender, EventArgs e)
    {
        // don't repopulate control on postbacks
        if (!IsPostBack)
        {
            // load search box controls' values
            string allWords = Request.QueryString["AllWords"];
            string searchString = Request.QueryString["Search"];
            if (allWords != null)
                allWordsCheckBox.Checked = (allWords.ToUpper() == "TRUE");
            if (searchString != null)
                searchTextBox.Text = searchString;
        }
    }
    protected void  goButton_Click(object sender, EventArgs e)
    {
        ExecuteSearch();
    }

    // Redirect to the search results page
    private void ExecuteSearch()
    {
        string searchText = searchTextBox.Text;
        bool allWords = allWordsCheckBox.Checked;

        if (searchTextBox.Text.Trim() != "")
        {
            searchText = HttpUtility.UrlEncode(searchText, Encoding.GetEncoding(28597)).Replace("+", " ");

            // remove all characters that aren't a-z, 0-9, dash, underscore or space
            searchText = purifyUrlRegex.Replace(searchText, "");
            Response.Redirect(Link.ToSearch(searchText, allWords, "1", "1"));

        }
    }
}